package com.joinval.modules.oss.minio;

import com.joinval.common.exception.JoinvalException;
import com.joinval.common.utils.DateUtils;
import io.minio.MinioClient;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class MinioUtils {

    @Autowired
    private MinioClient client;

    @Autowired
    private MinioProp minioProp;

    /**
     * 创建bucket
     *
     * @param bucketName bucket名称
     */
    @SneakyThrows
    public void createBucket(String bucketName) {
        if (!client.bucketExists(bucketName)) {
            client.makeBucket(bucketName);
        }
    }

    public void createBucketExt(String bucketName) {
        try {
            createBucket(bucketName);
        } catch (Exception e) {
            log.error("minioBucketExp:" + bucketName, e);
            throw new JoinvalException("调用MinIO文件系统过程中创建存储桶出错");
        }
    }

    /**
     * 随时间创建文件夹
     *
     * @param file       文件
     * @param bucketName 存储桶
     * @return
     */
    public String uploadFileWithDayDir(MultipartFile file, String bucketName) {
        // 文件名
        String originalFilename = file.getOriginalFilename();
        // 新的文件名 = 存储桶名称_时间戳.后缀名
        String fileName = DateUtils.getDateShort() + "/" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
        return uploadFile(file, bucketName, fileName);
    }

    /**
     * 随时间创建文件夹
     *
     * @param file       文件
     * @param bucketName 存储桶
     * @return
     */
    public String uploadFile(MultipartFile file, String bucketName) {
        // 文件名
        String originalFilename = file.getOriginalFilename();
        // 新的文件名 = 存储桶名称_时间戳.后缀名
        String fileName = DateUtils.getDate(System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf(".")));
        return uploadFile(file, bucketName, fileName);
    }

    public String uploadFileExt(MultipartFile file, String bucketName) throws Exception {
        // 判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
            return null;
        }
        // 文件名
        String originalFilename = file.getOriginalFilename();
        // 新的文件名 = 存储桶名称_时间戳.后缀名
        String fileName = System.currentTimeMillis() + "_" + RandomUtils.nextInt() +
                "_" + originalFilename.substring(originalFilename.lastIndexOf("."));
        return uploadFileExt(file, bucketName, DateUtils.getDateShort() + "/" + fileName);
    }

    /**
     * 上传文件
     *
     * @param file       文件
     * @param bucketName 存储桶
     * @return
     */
    public String uploadFile(MultipartFile file, String bucketName, String fileName) {
        // 判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
            throw new JoinvalException("上传文件不能为空！");
        }
        try {
            // 判断存储桶是否存在
            createBucket(bucketName);
        } catch (Exception e) {
            throw new JoinvalException("调用MinIO文件系统过程中判断存储桶出错！原因：" + e.getMessage());
        }
        // 开始上传
        try {
            client.putObject(bucketName, fileName, file.getInputStream(), file.getContentType());
        } catch (Exception e) {
            throw new JoinvalException("上传失败！原因：" + e.getMessage());
        }
        return bucketName + "/" + fileName;
    }

    /**
     * 上传文件
     *
     * @param file       文件
     * @param bucketName 存储桶
     * @return
     */
    public String uploadFileExt(MultipartFile file, String bucketName, String fileName) throws Exception {
        client.putObject(bucketName, fileName, file.getInputStream(), file.getContentType());
        return bucketName + "/" + fileName;
    }


    /**
     * 下载文件
     *
     * @param urls 文件URL
     * @return 下载的File对象，如果下载失败则返回null
     */
    public List<byte[]> downloadImagesToBytes(String urls) {
        List<byte[]> images = new ArrayList<>();
        String[] urlArray = urls.split(",");

        for (String url : urlArray) {
            url = url.trim();
            if (!url.isEmpty()) {
                byte[] imageBytes = downloadFileToBytes(url);
                if (imageBytes != null) {
                    images.add(imageBytes);
                } else {
                    System.out.println("Failed to download image from URL: " + url);
                }
            }
        }

        return images;
    }

    private byte[] downloadFileToBytes(String url) {
        String baseUrl = "http://58.34.179.115:9000";
        String fileUrl = String.format("%s/%s", baseUrl, url);
        try {
            URL downloadUrl = new URL(fileUrl);
            HttpURLConnection httpConn = (HttpURLConnection) downloadUrl.openConnection();
            int responseCode = httpConn.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                InputStream inputStream = httpConn.getInputStream();

                int nRead;
                byte[] data = new byte[16384];
                while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                    buffer.write(data, 0, nRead);
                }
                buffer.flush();

                inputStream.close();
                return buffer.toByteArray();
            } else {
                System.out.println("GET request not worked for URL: " + fileUrl);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
